from sys import meta_path
import xlrd
import os
from openpyxl import load_workbook
import re


class Excel2XmlTask:
    array_item_regex_array = {
        r"num_product_[0-9]+": ["num_product", "plurals", "quantity"],
        r"delete_or_cancel_[0-9]+": ["delete_or_cancel", "string-array", None],
        r"main_tab_titles_[0-9]+": ["main_tab_titles", "string-array", None],
    }
    special_item_label_array = ["one", "other"]

    def __init__(
        self,
        excelFileAbsPath,
        sheetName,
        xmlFileAbsPath,
        xmlFileType,
        keyColumnIndex=0,
        valueColumnIndex=2,
    ):
        """
        :param xmlFileType: xls 或 xlsx 后缀
        """
        self.excelFileAbsPath = excelFileAbsPath
        self.sheetName = sheetName
        self.xmlFileAbsPath = xmlFileAbsPath
        self.keyColumnIndex = keyColumnIndex
        self.valueColumnIndex = valueColumnIndex
        self.xmlFileType = xmlFileType

    def takeKey(self, elem):
        return elem[0]

    def run(self):
        if "xlsx" == self.xmlFileType:
            self.__runXlsx2()
        else:
            book = xlrd.open_workbook(self.excelFileAbsPath)
            sheet = book.sheet_by_name(self.sheetName)
            dir = self.xmlFileAbsPath[0 : self.xmlFileAbsPath.rindex("\\")]
            if not os.path.exists(dir):
                os.makedirs(dir)
            file = open(self.xmlFileAbsPath, "w")
            file.write('<?xml version="1.0" encoding="utf-8"?>\n<resources>\n')

            pair_list = []

            for rx in range(sheet.nrows):
                if rx <= 0:
                    continue
                row = sheet.row(rx)
                key = row[self.keyColumnIndex].value
                value = row[self.valueColumnIndex].value

                pair_list.append((key, value))
            pair_list.sort(key=self.takeKey)
            special_map = {}
            for rx in range(len(pair_list)):
                key = pair_list[rx][0]
                value = pair_list[rx][1]
                foundItem = None
                for __key in self.array_item_regex_array.keys():
                    regex = __key
                    if re.match(regex, key, re.I):
                        foundItem = __key
                        break
                if foundItem:
                    if foundItem in special_map:
                        special_map[foundItem].append(value)
                    else:
                        special_map[foundItem] = []
                        special_map[foundItem].append(value)

                else:
                    file.write('<string name="{0}">{1}</string>\n'.format(key, value))

            if len(special_map) > 0:
                for key in special_map.keys():
                    special_key = self.array_item_regex_array[key][0]
                    special_label = self.array_item_regex_array[key][1]
                    special_item_label = self.array_item_regex_array[key][2]
                    file.write('<{0} name="{1}">\n'.format(special_label, special_key))
                    index = 0

                    for value in special_map[key]:

                        if special_item_label:
                            file.write(
                                '<item {0}="{1}">{2}</item>\n'.format(
                                    special_item_label,
                                    self.special_item_label_array[index],
                                    value,
                                )
                            )
                            index = index + 1
                        else:
                            file.write("<item>{0}</item>\n".format(value))
                    file.write("</{0}>\n".format(special_label))

            file.write("</resources>")
            file.close()

    def __runXlsx(self):
        book = load_workbook(filename=self.excelFileAbsPath, read_only=True)
        sheet = book.get_sheet_by_name(self.sheetName)
        map = {}
        for row in range(1000):
            key = sheet.cell(row + 1, self.keyColumnIndex + 1).value
            if row <= 0:
                print("第一行", key)
                continue
            if key == None or key == "":
                continue
            value = sheet.cell(row + 1, self.valueColumnIndex + 1).value
            if key not in map:
                map[key] = value
        print(len(map))

    def __runXlsx2(self):
        book = load_workbook(filename=self.excelFileAbsPath, read_only=True)
        sheet = book.get_sheet_by_name(self.sheetName)
        special_re_array = [r"[\s\S]+success[\s\S]*", r"[\s\S]+failed[\s\S]*"]
        found_array = [[], []]
        map = {}
        for row in range(1000):
            if row <= 0:
                continue
            key = sheet.cell(row + 1, self.keyColumnIndex + 1).value
            if key == None or key == "":
                continue
            value = sheet.cell(row + 1, self.valueColumnIndex + 1).value
            if key in map:
                skip = False
                for mRe in special_re_array:
                    search_result = re.search(mRe, map[key])
                    if search_result:
                        skip = True
                        break
                if skip:
                    continue
                map[key] = value

            else:
                map[key] = value
        notFoundCount = 0
        for key in map.keys():
            value = map[key]
            found = False
            for i in range(len(special_re_array)):
                mRe = special_re_array[i]
                search_result = re.search(mRe, value)

                if search_result:
                    found = True
                    found_array[i].append(key)
                    break
            if not found:
                notFoundCount = notFoundCount + 1
                print(key, value)
        print(notFoundCount)
        for found in found_array:
            for item in found:
                print(item)
            print(len(found))
